package org.example.myleet.p468;

public class Solution {

    public static final String IPV4 = "IPv4";
    public static final String IPV6 = "IPv6";
    public static final String NEITHER = "Neither";

    public String validIPAddress(String queryIP) {
        queryIP = queryIP.toLowerCase();
        String[] parts;
        if (queryIP.contains(".")) {
            parts = queryIP.split("\\.");
            if (parts.length != 4) {
                return NEITHER;
            }
            if (queryIP.charAt(queryIP.length() - 1) == '.') {
                return NEITHER;
            }
            for (String part : parts) {
                if (part.length() < 1 || part.length() > 3 || (part.length() > 1 && part.charAt(0) == '0')) {
                    return NEITHER;
                }
                for (char c : part.toCharArray()) {
                    if (!Character.isDigit(c)) {
                        return NEITHER;
                    }
                }
                int i = Integer.parseInt(part);
                if (i < 0 || i > 255) {
                    return NEITHER;
                }
            }
            return IPV4;
        } else {
            parts = queryIP.split(":");
            if (parts.length != 8) {
                return NEITHER;
            }
            if (queryIP.charAt(queryIP.length() - 1) == ':') {
                return NEITHER;
            }
            for (String part : parts) {
                if (part.length() < 1 || part.length() > 4) {
                    return NEITHER;
                }
                for (char c : part.toCharArray()) {
                    if (Character.isAlphabetic(c)) {
                        if (c > 'f' && c <= 'z') {
                            return NEITHER;
                        }
                    }
                }
            }
            return IPV6;
        }
    }
}
